package com.wuuxiang.i5xforyou.service.kanjia.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuuxiang.i5xforyou.common.consts.Consts;
import com.wuuxiang.i5xforyou.common.domain.ResultMsg;
import com.wuuxiang.i5xforyou.common.domain.Results;
import com.wuuxiang.i5xforyou.common.service.impl.BaseServiceImpl;
import com.wuuxiang.i5xforyou.service.kanjia.KanJiaService;
import com.wuuxiang.i5xforyou.utils.HttpUtil;
import com.wuuxiang.i5xforyou.vo.kanjia.Activity;
import com.wuuxiang.i5xforyou.vo.kanjia.InfluenceRank;
import com.wuuxiang.i5xforyou.vo.kanjia.RankInfo;
import com.wuuxiang.i5xforyou.vo.kanjia.TradeResult;

/** 
 * @ClassName: KanJiaServiceImpl <br/>
 * 砍价活动service <br/>
 * @author Mobile Web Group-lff
 * @date 2018年3月15日 下午1:27:12
 *
 */
@Service("kanJiaService")
public class KanJiaServiceImpl extends BaseServiceImpl implements KanJiaService {
	
	/**
	 * Description: 砍价活动初始化页面数据
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月15日 下午2:34:33
	 * 
	 * @see com.wuuxiang.i5xforyou.service.kanjia.KanJiaService#init(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public ResultMsg init(String mpId, String openId, String campaignId, String initiatorOpenId, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		params.put("openId", openId);
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//入参
				params.put("initiatorOpenId", initiatorOpenId);//砍价活动发起人OpenId
				params.put("campaignId", campaignId);
				params.put("campaignTypeId", 10);//活动类型，10:砍价活动
				//调用接口
				url = Consts.CLOUD_API_URL + "rest/marketing/campaignbargin/single";
				resultJson = HttpUtil.doPostJSONObject(url, params.toJSONString());
				if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))) {
					//失败
					log.error("获取砍价活动初始化数据失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorMsg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//活动信息
				Activity activity = JSON.toJavaObject(resultJson, Activity.class);
				//根据活动状态设置提示的弹层信息
				activity.setStatusModalInfo();
				resultMsg.setMsgEntity(activity);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				JSONObject data = new JSONObject();
				data.put("initiatorOpenId", initiatorOpenId);//砍价活动发起人OpenId
				data.put("campaignId", campaignId);
				data.put("campaignTypeId", 18);//活动类型，18:砍价活动
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/single";
				//调用crm7接口查询单个活动（包含券列表）
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("获取砍价活动初始化数据失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				JSONObject content = resultJson.getJSONObject("content");
				Activity activity = JSON.toJavaObject(content, Activity.class);
				//根据活动状态设置提示的弹层信息
				activity.setStatusModalInfo();
				resultMsg.setMsgEntity(activity);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("获取砍价活动初始化数据失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	/**
	 * Description: 砍价操作
	 * @author: Mobile Web Group-LiuYandong
	 * @date: 2018年3月15日 下午2:34:33
	 */
	@Override
	public ResultMsg trade(String mpId, String openId,String userName, String campaignId, String initiatorOpenId,String profilePhotoImg, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		params.put("openId", openId);
		//出参
		JSONObject resultJson = new JSONObject();
		//出参
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//入参
				params.put("userName", userName);
				params.put("initiatorOpenId", initiatorOpenId);//砍价活动发起人OpenId
				params.put("campaignId", campaignId);
				params.put("profilePhotoImg", profilePhotoImg);
				//params.put("campaignTypeId", 10);//活动类型，10:砍价活动
				//调用接口
				url = Consts.CLOUD_API_URL + "rest/marketing/campaignbargin/trade";
				resultJson = HttpUtil.doPostJSONObject(url, params.toJSONString());
				/*if (resultJson.getIntValue("returnCode") != 1) {
					//失败
					log.error("砍价操作失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorText")));
					return resultMsg;
				}*/
				//成功
				TradeResult tradeResult = resultJson.toJavaObject(TradeResult.class);
				if(!tradeResult.createModalInfo(resultJson.getIntValue("errorCode"))) {
					//失败
					log.error("砍价操作失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorMsg")));
					return resultMsg;
				}
				resultMsg.setState(Results.SUCCESS);
				resultMsg.setFlag(tradeResult.takeStatus());
				resultMsg.setMsg(tradeResult.takeModalText());
				//活动信息
				resultMsg.setMsgEntity(tradeResult);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				JSONObject data = new JSONObject();
				data.put("initiatorOpenId", initiatorOpenId);//砍价活动发起人OpenId
				data.put("campaignId", campaignId);
				//data.put("campaignTypeId", 18);//活动类型，18:砍价活动
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/campaignBargain/process";
				//调用crm7接口查询单个活动（包含券列表）
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				//Crm7TradeResult crm7TradeResult = resultJson.toJavaObject(Crm7TradeResult.class);
				TradeResult tradeResult = new TradeResult();
				if(!tradeResult.createModalInfo(resultJson.getIntValue("code"))) {
					//失败
					log.error("砍价操作失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				if(resultJson.containsKey("content")) {
					JSONObject content = resultJson.getJSONObject("content");
					tradeResult = JSON.toJavaObject(content, TradeResult.class);
					tradeResult.createModalInfo(resultJson.getIntValue("code"));
				}
				resultMsg.setState(Results.SUCCESS);
				resultMsg.setFlag(tradeResult.takeStatus());
				resultMsg.setMsg(tradeResult.takeModalText());
				resultMsg.setMsgEntity(tradeResult);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("砍价操作失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	/**
	 * Description: 查询影响力排行榜
	 * @author: Mobile Web Group-lff
	 * @date: 2018年4月10日 下午12:55:19
	 * 
	 * @see com.wuuxiang.i5xforyou.service.kanjia.KanJiaService#influenceRank(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public ResultMsg influenceRank(String mpId, String openId, String campaignId, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		params.put("openId", openId);
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//入参
				params.put("campaignId", campaignId);
				//调用接口
				url = Consts.CLOUD_API_URL + "rest/marketing/campaignbargin/influenceRank";
				resultJson = HttpUtil.doPostJSONObject(url, params.toJSONString());
				if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))) {
					//失败
					log.error("查询影响力排行榜数据失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorMsg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//排行信息
				InfluenceRank influenceRank = JSON.toJavaObject(resultJson, InfluenceRank.class);
				resultMsg.setMsgEntity(influenceRank);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				JSONObject data = new JSONObject();
				data.put("campaignId", campaignId);
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/campaignBargain/influenceRank";
				//调用crm7接口
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("查询影响力排行榜数据失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				JSONObject content = resultJson.getJSONObject("content");
				//排行信息
				InfluenceRank influenceRank = toInfluenceRank(content);
				resultMsg.setMsgEntity(influenceRank);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("查询影响力排行榜数据失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	//接口返回值转为前端的数据类型
	private InfluenceRank toInfluenceRank(JSONObject content) {
		if (content == null) {
			return null;
		}
		//排行信息
		InfluenceRank influenceRank = new InfluenceRank();
		//top5
		JSONArray top5dataJsonArr = content.getJSONArray("top5data");
		if (top5dataJsonArr != null) {
			List<RankInfo> top5dataList = new ArrayList<RankInfo>();
			for (int i = 0; i < top5dataJsonArr.size(); i++) {
				JSONObject top5dataJson = top5dataJsonArr.getJSONObject(i);
				//top5排行信息
				RankInfo rankInfo = new RankInfo();
				rankInfo.setUserName(top5dataJson.getString("nickname"));
				rankInfo.setProfilePhotoImg(top5dataJson.getString("profilePic"));
				rankInfo.setCutToMoney(top5dataJson.getBigDecimal("allCutMoney"));
				rankInfo.setHelperNum(top5dataJson.getInteger("helperNum"));
				
				top5dataList.add(rankInfo);
			}
			influenceRank.setTop5data(top5dataList);
		}
		//我的排行
		JSONObject myRankInfoJson = content.getJSONObject("myRankingData");
		if (myRankInfoJson != null) {
			RankInfo myRankInfo = new RankInfo();
			myRankInfo.setMyRanking(myRankInfoJson.getInteger("myRanking"));
			myRankInfo.setCutToMoney(myRankInfoJson.getBigDecimal("cutToMoney"));
			myRankInfo.setHelperNum(myRankInfoJson.getInteger("helperNum"));
			
			influenceRank.setMyRankingData(myRankInfo);
		}
		
		return influenceRank;
	}
	
	/**
	 * Description: 查询帮砍排行榜
	 * @author: Mobile Web Group-lff
	 * @date: 2018年4月10日 下午12:55:19
	 * 
	 * @see com.wuuxiang.i5xforyou.service.kanjia.KanJiaService#helperRank(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public ResultMsg helperRank(String mpId, String openId, String campaignId, String crmVersion) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		params.put("openId", openId);
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			if (Consts.CRM6.equals(crmVersion)) {
				//入参
				params.put("campaignId", campaignId);
				//调用接口
				url = Consts.CLOUD_API_URL + "rest/marketing/campaignbargin/helperRank";
				resultJson = HttpUtil.doPostJSONObject(url, params.toJSONString());
				if (resultJson.getIntValue("returnCode") != 1 || !"200".equals(resultJson.getString("errorCode"))) {
					//失败
					log.error("查询帮砍排行榜数据失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("errorMsg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				//排行信息
				RankInfo[] helperRanks = JSON.toJavaObject(resultJson.getJSONArray("helpRankList"), RankInfo[].class);
				resultMsg.setMsgEntity(helperRanks);
				return resultMsg;
			} else if (Consts.CRM7.equals(crmVersion)) {
				//入参
				JSONObject data = new JSONObject();
				data.put("campaignId", campaignId);
				params.put("data", data);
				//调用接口
				url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/marketing/campaignBargain/helperRank";
				//调用crm7接口
				resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
				if (resultJson.getIntValue("code") != 200) {
					//失败
					log.error("查询帮砍排行榜数据失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
					resultMsg.setState(Results.ERROR);
					resultMsg.setException(new Exception(resultJson.getString("msg")));
					return resultMsg;
				}
				//成功
				resultMsg.setState(Results.SUCCESS);
				JSONArray content = resultJson.getJSONArray("content");
				//排行信息
				RankInfo[] helperRanks = toHelperRank(content);
				resultMsg.setMsgEntity(helperRanks);
				return resultMsg;
			} else {
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("没有查询到crm版本"));
				return resultMsg;
			}
		} catch (Exception e) {
			log.error("查询帮砍排行榜数据失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}
	
	//接口返回内容转为前端数据接口
	private RankInfo[] toHelperRank(JSONArray content) {
		if (content == null) {
			return null;
		}
		List<RankInfo> helperRankList = new ArrayList<RankInfo>();
		for (int i = 0; i < content.size(); i++) {
			JSONObject helperRankJson = content.getJSONObject(i);
			
			RankInfo helperRank = new RankInfo();
			helperRank.setUserName(helperRankJson.getString("nickname"));
			helperRank.setProfilePhotoImg(helperRankJson.getString("profilePic"));
			helperRank.setCutMoney(helperRankJson.getBigDecimal("cutMoney"));
			
			helperRankList.add(helperRank);
		}
		return helperRankList.toArray(new RankInfo[helperRankList.size()]);
	}
	
	
}
